import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
// 在 JS 代码中 @ 会解析成 src 的绝对路径
// import Reg from '@/views/Reg/Reg.vue'
// import Login from '@/views/Login/Login.vue'
// import Main from '@/views/Main/Main.vue'
// import Home from '@/views/Menus/Home/Home.vue'
// import UserInfo from '@/views/Menus/User/UserInfo.vue'
// import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
// import UserPwd from '@/views/Menus/User/UserPwd.vue'
// import ArtCate from '@/views/Menus/Article/ArtCate.vue'
// import ArtList from '@/views/Menus/Article/ArtList.vue'

// 导入登录注册组件

Vue.use(VueRouter)

// src/router/index.js 路由模块
Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

// 声明路由规则
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/Login.vue')
  },
  {
    path: '/reg',
    name: 'Reg',
    component: () => import('@/views/Reg/Reg.vue')
  },
  {
    path: '/',
    component: () => import('@/views/Main/Main.vue'),
    // 3. 开启路由重定向
    redirect: '/home',
    children: [
      // 2. home 作为 子路由规则
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/Menus/Home/Home.vue')
      },
      {
        path: 'user-info',
        name: 'UserInfo',
        component: () => import('@/views/Menus/User/UserInfo.vue')
      },
      {
        path: 'user-avatar',
        name: 'UserAvatar',
        component: () => import('@/views/Menus/User/UserAvatar.vue')
      },
      {
        path: 'user-pwd',
        name: 'UserPwd',
        component: () => import('@/views/Menus/User/UserPwd.vue')
      },
      {
        path: 'art-cate',
        name: 'ArtCate',
        component: () => import('@/views/Menus/Article/ArtCate.vue')
      },
      {
        path: 'art-list',
        name: 'ArtList',
        component: () => import('@/views/Menus/Article/ArtList.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由的前置导航守卫 路由切换之前进行拦截
router.beforeEach((to, from, next) => {
  const whiteList = ['/login', '/reg']
  if (!whiteList.includes(to.path) && !store.state.token) {
    Vue.prototype.$message.error('请登录！')
    next('/login')
  }
  next()
})

export default router
